<template>
  <div class="app-container">
    <!-- 查询表单开始 -->
    <el-form ref="formSearch" :model="queryParams" label-width="100px">
      <el-row>
        <el-col v-for="(item, index) in option.queryFormFields" :key="item.field" :span="item.span || 6">
          <el-form-item v-if="index <= 2 || (index > 2 && queryParams.showMoreSearch)" :label="item.label" :rules="item.rules" :prop="item.field" :disabled="item.disabled">
            <!-- 输入框 -->
            <el-input v-if="item.inputType == 'input'" v-model.trim="queryParams[item.field]" :placeholder="item.placeholder || $t('placeholder.input')" :clearable="item.clearable !== false" />
            <!-- 下拉框 -->
            <anji-select v-else-if="item.inputType == 'anji-select'" v-model.trim="queryParams[item.field]" :dict-code="item.anjiSelectOption.dictCode" :url="item.anjiSelectOption.url" :option="item.anjiSelectOption.option" :label="item.anjiSelectOption.label" />
            <!-- 日期时间框  -->
            <el-date-picker v-else-if="item.inputType.indexOf('date') >= 0" v-model="queryParams[item.field]" style="width: 100%" :placeholder="item.placeholder || $t('placeholder.select')" :type="item.inputType" :clearable="item.clearable !== false" />
            <!-- 待扩展的表单类型，请自行扩展 -->
            <el-input v-else placeholder="组件不支持此类型表单请至组件内部自行扩展" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="5" style="text-align: center">
          <el-button type="primary" @click="handleQueryPageList()">{{ $t('btn.query') }}</el-button>
          <el-button type="danger" @click="handleResetForm()">{{ $t('btn.reset') }}</el-button>
          <a style="margin-left: 8px" @click="handleToggleMoreSearch">
            {{ queryParams.showMoreSearch == true ? '收起' : '展开' }}
            <i :class="queryParams.showMoreSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
          </a>
        </el-col>
      </el-row>
    </el-form>
    <!-- 查询表单结束 -->

    <!-- 批量操作 -->
    <el-button v-permission="option.buttons.add.permission" type="primary" icon="el-icon-plus" @click="handleOpenEditView('add')">{{ $t('btn.add') }}</el-button>
    <el-button v-permission="option.buttons.delete.permission" :disabled="disableBatchDelete" type="danger" icon="el-icon-delete" @click="handleDeleteBatch()">{{ $t('btn.delete') }}</el-button>

    <!-- 表格开始 -->
    <el-table :data="records" border @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="50" align="center" />
      <el-table-column label="序号" min-width="50" align="center">
        <template slot-scope="scope">
          {{ queryParams.pageSize * (queryParams.pageNumber - 1) + scope.$index + 1 }}
        </template>
      </el-table-column>
      <template v-for="(item, index) in option.columns">
        <el-table-column v-if="item.tableHide != true" :key="item.field" :label="item.label" :min-width="item.minWidth || 110" align="center">
          <template slot-scope="scope">
            <!-- 正常展示模式 -->
            <div v-if="!item.custom">
              <!-- 是第一列数据 && 需要高亮字段不为false 高亮并且可以点击 -->
              <span v-if="!index && item.operate !== false" class="view" @click="handleOpenEditView('view', scope.row)">{{ scope.row[item.field] }}</span>
              <span v-else>{{ scope.row[item.field] }}</span>
            </div>
            <!-- 自定义展示数据 -->
            <div v-else v-html="item.renderer(scope.row)" />
          </template>
        </el-table-column>
      </template>
      <el-table-column prop="createTime" :label="$t('businessGlossary.creationTime')" align="center" min-width="160" />
      <el-table-column prop="createByView" :label="$t('businessGlossary.creator')" align="center" min-width="160" />
      <el-table-column prop="updateTime" :label="$t('businessGlossary.modifyTime')" align="center" min-width="180" />
      <el-table-column prop="createByView" :label="$t('businessGlossary.modifyUser')" align="center" min-width="140" />
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleOpenEditView('edit', scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDeleteBatch(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="total > 0" background :current-page.sync="queryParams.pageNumber" :page-sizes="$pageSizeAll" :page-size="queryParams.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-- 表格结束 -->

    <EditDialog :option="option" :model-type="editDialogModelType" :open-dialog="editDialogOpen" :query-params="editDialogQueryParams" @closeEvent="handleQueryPageList" />
  </div>
</template>
<script>
import { cloneDeep } from 'loadsh'
import EditDialog from './edit'
export default {
  components: {
    EditDialog,
  },
  props: {
    option: {
      require: true,
      type: Object,
      default: () => {
        return {
          // 查询表单条件
          queryFormFields: [],
          // 按钮
          buttons: {
            query: {},
            edit: {},
            delete: {},
            add: {},
          },
          // 表格列
          columns: [],
          // 弹框配置
          editDialog: {},
        }
      },
    },
  },
  data() {
    return {
      // 查询表单提交的值
      queryParams: {
        showMoreSearch: false, // 是否展开更多搜索条件
        pageNumber: 1,
        pageSize: 10,
      },

      checkRecords: [], // 表格中当前选中的记录
      records: [], // 接口返回的记录列表
      total: 0, // 接口返回的总条数

      // 编辑详情弹框
      editDialogOpen: false, // 新建时主动打开编辑弹框
      editDialogQueryParams: {}, // 编辑时的主键
      editDialogModelType: 'view', // 编辑 查看
    }
  },
  computed: {
    // 主键的列名
    primaryKeyFieldName() {
      var primaryKey = this.option.columns.find((item) => item['primaryKey'] == true)
      if (primaryKey != null) {
        return primaryKey['field']
      } else {
        return null
        console.warn('在columns中查找primaryKey=true失败，会导致查询详情和删除失败')
      }
    },
    // 是否可以批量删除
    disableBatchDelete() {
      return this.checkRecords.length <= 0
    },
  },
  created() {
    this.option.queryFormFields.forEach((item) => {
      // 动态添加属性
      this.$set(this.queryParams, item.field, item.fieldValue || null)
    })
    this.handleQueryPageList()
    console.log(this.primaryKeyFieldName)
  },
  methods: {
    // 切换更多搜索条件
    handleToggleMoreSearch() {
      this.queryParams.showMoreSearch = !this.queryParams.showMoreSearch
    },
    // 查询
    async handleQueryPageList() {
      const { data, code } = await this.option.buttons.query.api(this.queryParams)
      if (code != '200') return
      this.records = data.records
      this.total = data.total
    },
    // 重置
    handleResetForm() {
      this.$refs['queryForm'].resetFields()
      this.records = []
      this.total = 0
    },

    // 编辑和查看操作
    handleOpenEditView(modelType, row) {
      if (modelType == 'view' || modelType == 'edit') {
        this.editDialogQueryParams = row
      }
      this.editDialogModelType = modelType
      if (modelType == 'add') {
        // 新增模式，不需要查询数据详情，直接打开
        this.editDialogOpen = true
      }
    },

    // 批量删除
    handleDeleteBatch(row) {
      var ids = []
      if (row != null) {
        ids.push(row[this.primaryKeyFieldName]) // 删除指定的行
      } else {
        // 批量删除选中的行
        ids = this.checkRecords.map((item) => item[this.primaryKeyFieldName])
      }
      this.$confirm(this.$t('promptMessage.deleteTip'), this.$t('promptMessage.deleteTipTitle'), {
        type: 'warning',
        confirmButtonClass: 'delete_sure',
        cancelButtonClass: 'el-button--danger is-plain',
      })
        .then(() => {
          this.option.buttons.delete.api(ids).then((res) => {
            // {code: "200", message: "操作成功", data: true}
            this.checkRecords = []
            this.handleQueryPageList()
          })
        })
        .catch((e) => {
          e
        })
    },

    // 选择项改变时
    handleSelectionChange(val) {
      this.checkRecords = val
      console.log(this.checkRecords)
    },
    // 页码改变
    handleCurrentChange(pageNumber) {
      this.queryParams.pageNumber = pageNumber
      this.handleQueryPageList()
    },
    // 每页size改变时
    handleSizeChange(val) {
      this.queryParams.pageNumber = 1
      this.queryParams.pageSize = val
      this.handleQueryPageList()
    },
  },
}
</script>
